<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{

	public function __construct()
	{
		parent::__construct();

		// Load all the required classes
		$this->load->model('dataman_m');
		$this->load->library('form_validation');
		$this->lang->load('dataman');
		$this->load->library('pagination');
		$this->load->library('module_helper');
		
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
						->append_metadata(js('admin.js', 'dataman'))
						->append_metadata(css('admin.css', 'dataman'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		$this->template->title($this->module_details['name'])->build('admin/items', $this->data);
	}
	
/*////////////////////////////////////////CONTENT SECTION//////////////////////////////////////////*/
	public function content()
	{
		$key_query = (isset($_GET['keyword'])) ? $_GET['keyword']: '';
		$type= (isset($_GET['type']))? $_GET['type']: '';
		
		if(!$key_query AND !$type){
			$config['base_url'] = site_url().'admin/dataman/content/';
			$config['total_rows'] = $this->dataman_m->get_total_content_records();
			$config['per_page'] = '25';
			$config['full_tag_open'] = '<div id="pagination">';
			$config['full_tag_close'] = '</div>';
			$config['first_link'] = 'First';
			$config['last_link'] = 'Last';
			$config['next_link'] = '&gt';
			$config['prev_link'] = '&lt';
			$config['cur_tag_open'] = '<div class="cur">';
			$config['cur_tag_close'] = '</div>';
			$config['uri_segment'] = '4';
			 
			$this->pagination->initialize($config);
		 	$contents = $this->dataman_m->get_content( $config['per_page'] , $this->uri->segment(4) );
			$this->data->contents =& $contents;
			$this->data->pagination = $this->pagination->create_links();
		}else{
			$this->data->pagination = '';
			
			$type_arr = array('id','name','region','city','created_user','modified_user');
			if(!in_array($type, $type_arr)){
				$type= 'name';
			}
			
			$contents = $this->dataman_m->search_content( $key_query , $type );
			$this->data->contents =& $contents;
		}
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.content'))
						->build('admin/content', $this->data);
	}
	
	function content_edit_item(){
		$id= intval($this->uri->segment(4));
		$result= $this->db->where('id', $id)->get('ff_rs_content')->result();
		
		$this->data->record= $result[0];
		$this->data->region= $this->dataman_m->_regions($result[0]->region_id);
		$this->data->city= $this->dataman_m->_cities($result[0]->region_id, $result[0]->city_id);
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.content'))
						->build('admin/content/edit', $this->data);
	}
	
	public function aj_check_duplicate_name(){
	 	$name = $_POST['name'];
		$item_id = intval($_POST['item_id']) ;
	 
		$r = $this->db->where('name',$name)->get('ff_rs_content')->result();
		 
		if($item_id == 0){
			if(!empty($r))
				echo 'false';
			else 
				echo 'ok';
		}else{
			if( count($r) <= 1 ){
				echo 'ok';
			}else{
				echo 'false';
			}
		}
		exit();
	}
	
	function aj_save_content(){
		$data = $_POST['data'];
		
		$arr = array();
		foreach ($data as $value) {
			$arr[$value['name']]= $value['value'];
		}
		
		settype($arr,'object');
		
		$tempPath = './uploads/files/tmp/';
		$storePath = './uploads/files/pictures/';
			
		if($arr->item_id != 0){ // case update
			$old = $this->db->where('id',$arr->item_id)->get('ff_rs_content')->result();
			
			if( $arr->image_uploaded_1 != $old[0]->image1 ){
				$pic1 = $this->module_helper->uploadFile( $tempPath.$arr->image_uploaded_1,
													  $arr->image_uploaded_1,
													  $storePath,''		
													);
		 		$this->_move_to_store_picture($tempPath.$arr->image_uploaded_1, $storePath.$pic1);
			}else{
				$pic1 = $old[0]->image1;
			}
			
			if( $arr->image_uploaded_2 != $old[0]->image2 ){
				$pic2 = $this->module_helper->uploadFile( $tempPath.$arr->image_uploaded_2,
													  $arr->image_uploaded_2,
													  $storePath,''		
													);
		 		$this->_move_to_store_picture($tempPath.$arr->image_uploaded_2, $storePath.$pic2);
			}else{
				$pic2 = $old[0]->image2;
			}
			
			if( $arr->image_uploaded_3 != $old[0]->image3 ){
				$pic3 = $this->module_helper->uploadFile( $tempPath.$arr->image_uploaded_3,
													  $arr->image_uploaded_3,
													  $storePath,''		
													);
		 		$this->_move_to_store_picture($tempPath.$arr->image_uploaded_3, $storePath.$pic3);
			}else{
				$pic3 = $old[0]->image3;
			}
			
			$iChoose = 1;
			for($j= 1;$j<= 3;$j++){
				$e= "image_selected$j";
				if(isset($arr->$e) AND $arr->$e == 1){
					$iChoose = $j;  
				}
			}
			 
			$array_update = array ( 	'name'=> $arr->name_item ,
										'dish_name'=> $arr->dish_name,
										'region_id' => $arr->region,
										'city_id' =>  $arr->city,
										'details' =>  $arr->details,
										'url' =>  $arr->user_url,
										'main_picture' => $iChoose,
										'image1' => $pic1, 'image2' => $pic2, 'image3' => $pic3,
										'modified_by_id' => $arr->modify_user_id,
									//	'modified_time' => time(),
										'longitude' => floatval( $arr->long ),
										'latitude' => floatval( $arr->lat ),
										'elsewhat' => $arr->elsewhat
									);
			$this->db->where('id',$arr->item_id)->update('ff_rs_content',$array_update);
			$this->session->set_flashdata('success', lang('dataman.success'));
			 
			echo site_url().'admin/dataman/content_edit_item/'.$arr->item_id;
		}
		else{ // case create new content
			$pic1 = $this->module_helper->uploadFile( $tempPath.$arr->image_uploaded_1,
												  $arr->image_uploaded_1,
												  $storePath,''		
												);
		 	$this->_move_to_store_picture($tempPath.$arr->image_uploaded_1, $storePath.$pic1);
			 
			$pic2 = $this->module_helper->uploadFile( $tempPath.$arr->image_uploaded_2,
													  $arr->image_uploaded_2,
													  $storePath,''		
													);
		 	$this->_move_to_store_picture($tempPath.$arr->image_uploaded_2, $storePath.$pic2);
			 
			$pic3 = $this->module_helper->uploadFile( $tempPath.$arr->image_uploaded_3,
													  $arr->image_uploaded_3,
													  $storePath,''		
													);
		 	$this->_move_to_store_picture($tempPath.$arr->image_uploaded_3, $storePath.$pic3);
			
			$iChoose = 1;
			for($j= 1;$j<= 3;$j++){
				$e= "image_selected$j";
				if(isset($arr->$e) AND $arr->$e == 1){
					$iChoose = $j;  
				}
			}
		 
			$array_insert = array ( 	'name'=> $arr->name_item ,
										'dish_name'=> $arr->dish_name,
										'region_id' => $arr->region,
										'city_id' =>  $arr->city,
										'details' =>  $arr->details,
										'url' =>  $arr->user_url,
										'main_picture' => $iChoose,
										'image1' => $pic1, 'image2' => $pic2, 'image3' => $pic3,
										'created_by_id' => $arr->post_user_id,
										'created_time' => time(),'modified_time'=> time(),
										'longitude' => floatval( $arr->long ),
										'latitude' => floatval( $arr->lat ),
										'elsewhat' => $arr->elsewhat
									);
			$this->db->insert( 'ff_rs_content', $array_insert );
			$this->session->set_flashdata('success', lang('dataman.success'));
			
			$just_inserted_id = $this->db->insert_id();
			echo site_url().'admin/dataman/content_edit_item/'.$just_inserted_id;
		}
		exit();
	}
	
	public function iF_proc_image_preview(){
		$i = intval( $this->uri->segment(4,0) ) ;
		 
		$uploadPath = './uploads/files/tmp/';
		$conf['allowed_types'] =  array( "jpg", "jpeg", "png", "gif", "bmp" );
		$conf['max_size'] = 8000;
		
		if( ($_FILES["image$i"]['size']/1024) > $conf['max_size'] ){
			$image = '';
		}else{
			$image = $this->module_helper->uploadFile(
													$_FILES["image$i"]['tmp_name'], 
												 	$_FILES["image$i"]['name'],
													$uploadPath,
													$conf['allowed_types']
												);
		}
		if($image != ''){
			$link = (site_url().'uploads/files/tmp/timthumb.php?w=150&h=100&zc=1&src='.
							site_url().'uploads/files/tmp/'.$image);
							
			$preview = "<img src='".$link."' />";
			 
			$rs_ar	 = array('status'=>'ok','source'=>$preview,'hidden_id'=>"image_uploaded_$i",'value'=>$image);				
			 
		}else{
			$rs_ar	= array('status'=>'error','reasonwhy'=>lang('ranking.add.form.image.upload.error'),
							'hidden_id'=>"image_uploaded_$i",'value'=>'' );
		}
		
		echo implode('SEP_CHAR', $rs_ar);
		//echo json_encode($rs_ar);
	}
	
	private function _move_to_store_picture( $tempPath_File , $storePath_file ){
		//rename($tempPath_File , $storePath_file);
		@copy($tempPath_File , $storePath_file);
	} 
	
	function content_update(){
		$this->data->region= $this->dataman_m->_regions($selected_id = 0 );
		$this->data->city= $this->dataman_m->_cities($region_id = -1 , $selected_id = 0);
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.content'))
						->build('admin/content/create', $this->data);
	}
		
	function content_delete_item(){
		$id = intval($this->uri->segment(4));
		
		//select collection id
		$result= $this->db->query("SELECT id FROM rs_connection WHERE upper_content_id=$id OR lower_content_id=$id")->result();
		
		$tmp_arr = array();
		foreach($result as $one){
			$tmp_arr[]= $one->id;
		}
		
		$list_id= implode(',', $tmp_arr);
		//delete from rs_temp_post
		$tmp_arr= array_filter($tmp_arr);
		if(!empty($tmp_arr)){
			$this->db->query("DELETE FROM rs_post WHERE connection_id IN($list_id)");
			$this->db->query("DELETE FROM rs_connection WHERE id IN($list_id)");
			$this->db->query("DELETE FROM ff_rs_content WHERE id=$id");
		}else {
			$this->db->query("DELETE FROM ff_rs_content WHERE id=$id");
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url('admin/dataman/content'));
	}
	
	function content_set_top_stand(){
		$id = intval($_POST['id']);
		$r = $this->db->where('id',$id)->get('ff_rs_content')->result();
		$old = intval($r[0]->is_top_stand);
		
		$this->db->query("UPDATE ff_rs_content SET is_top_stand='0' ");
		
		$this->db->query("UPDATE ff_rs_content SET is_top_stand= ABS($old-1) WHERE id=$id");
		//$this->db->where('id',$id)->update('ff_rs_content',array('is_top_stand'=>1));
		
		$this->session->set_flashdata('success', lang('dataman.success'));
		echo lang('dataman.success');
		exit();
	}	
	/*/////////////////////////////////AREA SECTION //////////////////////////////////////*/
	function area(){
		$config['base_url'] = site_url().'admin/dataman/area/';
		$config['total_rows'] = $this->dataman_m->get_total_state_records();
		$config['per_page'] = '25';
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = '&gt';
		$config['prev_link'] = '&lt';
		$config['cur_tag_open'] = '<div class="cur">';
		$config['cur_tag_close'] = '</div>';
		$config['uri_segment'] = '4';
		 
		$this->pagination->initialize($config);
	 	$contents = $this->dataman_m->get_state( $config['per_page'] , $this->uri->segment(4) );
		$this->data->contents =& $contents;
		$this->data->pagination = $this->pagination->create_links();
		
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.area'))
						->build('admin/area_state', $this->data);
	}	
	
	function state_edit(){
		$id = intval($this->uri->segment(4));
		$result = $this->db->where('id',$id)->get('ff_regions')->result();
		
		$this->data->state= $result[0];
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.area'))
						->build('admin/area/state_form', $this->data);
	}
	
	function area_state_update(){
		$tmp = (object) array('id'=>0,'name'=>'');
		 
		$this->data->state= $tmp;
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.area'))
						->build('admin/area/state_form', $this->data);
	}
	
	function state_update(){
		$id= intval($this->input->post('id'));
		$region= $this->input->post('name');
		
		if($id !=0){
			$this->db->where('id',$id)->update('ff_regions',array('name'=>$region));
		}else{
			$this->db->insert('ff_regions',array('name'=>$region));
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url('admin/dataman/area'));
	}
	
	function state_delete(){
		$id = intval($this->uri->segment(4));
		$this->db->where('id',$id)->delete('ff_regions');
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url('admin/dataman/area'));
	}
	
	function city_view(){
		$config['base_url'] = site_url().'admin/dataman/city_view/';
		$config['total_rows'] = $this->dataman_m->get_total_cities_records();
		$config['per_page'] = '25';
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = '&gt';
		$config['prev_link'] = '&lt';
		$config['cur_tag_open'] = '<div class="cur">';
		$config['cur_tag_close'] = '</div>';
		$config['uri_segment'] = '4';
		 
		$this->pagination->initialize($config);
	 	$contents = $this->dataman_m->get_cities( $config['per_page'] , $this->uri->segment(4) );
		$this->data->contents =& $contents;
		$this->data->pagination = $this->pagination->create_links();
		
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.area'))
						->build('admin/area_cities', $this->data);
	}
	
	function city_edit(){
		$id = intval($this->uri->segment(4));
		$result = $this->db->where('id',$id)->get('ff_cities')->result();
		
		$this->data->cities= $result[0];
		$this->data->state= $this->db->get('ff_regions')->result(); 
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.area'))
						->build('admin/area/city_form', $this->data);
	}
	
	function city_update(){
		$id = intval($this->input->post('id'));
		$region_id = $this->input->post('region_id');
		$city = $this->input->post('city');
		
		if($id != 0){
			$this->db->where('id',$id)->update('ff_cities',array('region_id'=>$region_id,'city'=>$city));
		}else{
			$this->db->insert('ff_cities',array('region_id'=>$region_id,'city'=>$city));
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url('admin/dataman/city_view'));
	}
	
	function area_city_update(){
		$arr_obj = (object) array('id'=>0,'city'=>'','region_id'=>1);
		
		$this->data->cities= $arr_obj;
		$this->data->state= $this->db->get('ff_regions')->result(); 
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.area'))
						->build('admin/area/city_form', $this->data);
	}
	
	function city_delete(){
		$id = intval($this->uri->segment(4));
		$this->db->where('id',$id)->delete('ff_cities');
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url('admin/dataman/city_view'));
	}
	
	/*////////////////////////////////////////CONNECTION AREA/////////////////////////////////*/
	function connection(){
		$config['base_url'] = site_url().'admin/dataman/connection/last_posted_time/desc/';
		$config['total_rows'] = $this->dataman_m->get_total_connection_records();
		$config['per_page'] = '25';
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = '&gt';
		$config['prev_link'] = '&lt';
		$config['cur_tag_open'] = '<div class="cur">';
		$config['cur_tag_close'] = '</div>';
		$config['uri_segment'] = '6';
		 
		$this->pagination->initialize($config);
	 	$contents = $this->dataman_m->get_connection( $config['per_page'] , $this->uri->segment(6),
	 									$orderField= $this->uri->segment(4),$order= $this->uri->segment(5));
		$this->data->contents =& $contents;
		$this->data->pagination = $this->pagination->create_links();
		$this->data->link = $this->order_link();
		
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.area'))
						->build('admin/connection', $this->data);
	}
	
	function order_link(){
		$order= $this->uri->segment(5);
		if( $order == '' || $order == 'asc'){
			$order = 'desc';
		}else{
			$order = 'asc';
		}
		
		$obj =(object) array( 'upper_content_id'=>site_url('admin/dataman/connection/upper_content_id/'.$order.'/'),
					  'lower_content_id'=>site_url("admin/dataman/connection/lower_content_id/$order/"),
					  'last_posted_time'=>site_url("admin/dataman/connection/last_posted_time/$order/"),
					  'weight'=>site_url("admin/dataman/connection/weight/$order/")		 	
					);
		return $obj;
	}
	
	function connection_edit(){
		$id = intval($this->uri->segment(4));
		$result = $this->db->where('id',$id)->get('rs_connection')->result();
		
		$this->data->connect= $result[0];
		 $this->data->option = $this->db->get('ff_rs_content')->result();
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.connection'))
						->build('admin/connection/form', $this->data);
	}
	
	function connection_add(){
		$this->data->connect= (object) array('id'=>0,'upper_content_id'=>'','lower_content_id'=>'','weight'=>0);
		// Load the view
		$this->data->option = $this->db->get('ff_rs_content')->result();
		$this->template->title($this->module_details['name'], lang('dataman.connection'))
						->build('admin/connection/form', $this->data);
	}
	
	function connection_update(){
		$ar = array('upper_content_id','lower_content_id','weight','id');
		foreach ($ar as $val){
			$$val = intval( $this->input->post($val) );
		}
		 
	/*	if($id != 0){
			$this->db->where('id',$id)->update('rs_connection',
								array(
								'upper_content_id'=>$upper_content_id,
								'lower_content_id'=>$lower_content_id,
								'weight'=>$weight,
								'last_posted_time'=>time()
								));
		}else{
			$this->db->insert('rs_connection',
								array(
								'upper_content_id'=>$upper_content_id,
								'lower_content_id'=>$lower_content_id,
								'weight'=>$weight,
								'last_posted_time'=>time()
								));
		}
		*/
		$this->update_connection($high=$upper_content_id, $low=$lower_content_id, $user_id=1, $weight);
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url('admin/dataman/connection/last_posted_time/desc/'));
	}
	
	function check_and_process_user_posted($connection_id, $user_id, $connection_id_reserve){
		//check
		$r= $this->db->query("SELECT * FROM rs_post WHERE connection_id=$connection_id AND user_id=$user_id")->result();
		if(empty($r)){ //insert
			$this->db->insert('rs_post', array('connection_id'=>$connection_id, 'user_id'=>$user_id, 'posted_time'=>time(), 'is_connected'=>1 ) );
			if($connection_id_reserve != 0){
				$this->db->where(array('connection_id'=>$connection_id_reserve,'user_id'=>$user_id))->update('rs_post',array('is_connected'=> 0) ) ;	
			}
		}
		
		//check
		$r2= $this->db->query("SELECT * FROM rs_temp_post WHERE connection_id=$connection_id AND user_id=$user_id")->result();
		if(empty($r)){ //insert
			$this->db->insert('rs_temp_post', array('connection_id'=>$connection_id, 'user_id'=>$user_id, 'posted_time'=>time() ) );
		}
		$this->update_user_ranking($connection_id, $user_id);
		
		return true;
	}
	
	function update_user_ranking($connection_id, $user_id){
	/*	$u_rc = $this->db->where('id',$user_id)->get('ff_users_fb')->result();
		$conn_id_arr = array();
		
		$mix_arr = explode(';', $u_rc[0]->user_ranking );
		foreach($mix_arr as $e){
			$tmp = explode(',', $e);
			$conn_id_arr[] = $tmp[0];
		}
		if(empty($conn_id_arr)){
			$push_e = "$connection_id,0";
			array_push($mix_arr, $push_e);
		}else{
			if(!in_array($connection_id, $conn_id_arr)){
				$push_e = "$connection_id,0";
				array_push($mix_arr, $push_e);
			}
		}
		$mix_arr = array_filter($mix_arr);
		$user_ranking = implode(';', $mix_arr); 
		$this->db->where('id',$user_id)->update('ff_users_fb',array('user_ranking'=>$user_ranking));
		return;
	*/	
	}
	
	function update_connection($high, $low, $user_id, $weight){
	// check if existed in database upper_content_id:== $high AND lower_content_id:== $low
		$result_obj_AB= $this->db->query("SELECT * FROM `rs_connection` WHERE rs_connection.upper_content_id= $high AND rs_connection.lower_content_id= $low ")->result();
		
		// check if existed in database upper_content_id:== $low AND lower_content_id:== $high
		$result_obj_BA= $this->db->query("SELECT * FROM `rs_connection` WHERE rs_connection.upper_content_id= $low AND rs_connection.lower_content_id= $high ")->result();
		
		if(!empty($result_obj_AB)){
			$this->db->where( 'id', $result_obj_AB[0]->id )->update('rs_connection', array('last_posted_time'=> time(), 'weight'=>$weight));
			$this->update_user_ranking($result_obj_AB[0]->id, $user_id);
		}
		
		if(!empty( $result_obj_BA )){
			$id_BA = $result_obj_BA[0]->id;
		}else{
			$id_BA = 0;
		}
		
		$time = time();
		$this->db->where('id',$high)->update('ff_rs_content',array('modified_time'=>$time));
		$this->db->where('id',$low)->update('ff_rs_content',array('modified_time'=>$time));
		//
		if( !empty($result_obj_AB) AND $result_obj_AB[0]->is_connected == 1 ){
		//	$this->db->where( 'id', $result_obj_AB[0]->id )->update('rs_connection', array('weight'=> $result_obj_AB[0]->weight + 1));
			$this->db->where( 'id', $result_obj_AB[0]->id )->update('rs_connection', array('last_posted_time'=> time()));
			
		//	$this->check_and_process_user_posted($result_obj_AB[0]->id, $user_id);
			return TRUE;
		}
		elseif( !empty($result_obj_AB) AND $result_obj_AB[0]->is_connected == 0 AND !empty($result_obj_BA) AND $result_obj_BA[0]->is_connected == 1){
			if( $result_obj_AB[0]->weight + 1 < $result_obj_BA[0]->weight ){
			//	$this->db->where( 'id', $result_obj_AB[0]->id )->update('rs_connection', array('weight'=> $result_obj_AB[0]->weight + 1));
				$this->db->where( 'id', $result_obj_AB[0]->id )->update('rs_connection', array('last_posted_time'=> time()));
				
			//	$this->check_and_process_user_posted($result_obj_AB[0]->id, $user_id);
				return TRUE;
			}
		}// else if empty A> B : insert to rs_connection and rs_temp_post and rs_post
		elseif( empty($result_obj_AB) ){
			$this->db->insert('rs_connection', array('upper_content_id'=> $high, 
													 'lower_content_id'=> $low,
													 'last_posted_time'=> time(),
													 'weight'=> $weight ,
													 'is_connected'=> 0 
													)
							 );
			$temp_post_connection_id= $this->db->insert_id();
			
			$this->check_and_process_user_posted($temp_post_connection_id, $user_id, $id_BA);
			return TRUE;
		}
	/*	
		//check if 
		$result_obj= $this->db->query("SELECT * FROM `rs_connection` INNER JOIN rs_post ON rs_connection.id=rs_post.connection_id WHERE rs_connection.upper_content_id= $high AND rs_connection.lower_content_id= $low AND rs_post.user_id=$user_id")->result();
		
		//if not exist
		if(empty($result_obj)){
			$this->db->insert('rs_connection', array('upper_content_id'=> $high, 
													 'lower_content_id'=> $low,
													 'last_posted_time'=> time(),
													 'weight'=> 1 ,
													 'is_connected'=> 0 
													)
							 );
			$temp_post_connection_id= $this->db->insert_id();				 
		}
		else{
			//check if user had inserted 
			$users_arr = array();
			$r= $this->db->where('connection_id',$result_obj[0]->id)->get('rs_post')->result();
			foreach($r as $o){
				$users_arr[] = $one->user_id;
			}
		//	$users_arr= explode(',', $result_obj[0]->posted_by);
			//if true
			if(in_array($user_id, $users_arr)){
				//update last_posted_time
				$this->db->where('id', $result_obj[0]->id)->update('rs_connection', array('last_posted_time'=>time()));
			} 
			else{
				//push user
			//	array_push($users_arr, $user_id);
			//	$this->db->where('id', $result_obj[0]->id)->update('rs_connection', array('last_posted_time'=>time(), 'posted_by'=>implode(',', $users_arr)));
				$this->db->insert('rs_post', array('connection_id'=>$result_obj[0]->id, 'user_id'=>$user_id, 'posted_time'=>time() ) );
			}
			
			$temp_post_connection_id= $result_obj[0]->id;
		}
		
		// Now insert connection_id into `rs_temp_post`
		$res= $this->db->query("SELECT * FROM rs_temp_post WHERE connection_id= $temp_post_connection_id AND user_id= $user_id")->result();
		if(empty($res)){
			$this->db->insert('`rs_temp_post`',array(
									'connection_id'=> $temp_post_connection_id,
									'user_id'=> $user_id,
									'posted_time'=> time()
								)

			);
		}
		else{
			$this->db->query("UPDATE rs_temp_post SET posted_time=".time()." WHERE connection_id= $temp_post_connection_id AND user_id= $user_id");
		}
		return true;	
		$is_reverse = $this->db->query("SELECT rs_connection.*,rs_post.* FROM rs_connection INNER JOIN rs_post ON rs_connection.id=rs_post.connection_id
		 WHERE lower_content_id=$high AND upper_content_id=$low AND user_id=$user_id")->result();

		if(!empty($is_reverse)){
			//delete at rs_post
			$this->db->where(array('connection_id'=>$is_reverse[0]->connection_id,'user_id'=>$user_id))->delete('rs_post');
			//decrease -1 at rs_connection
			$this->db->where('id',$is_reverse[0]->id)->update('rs_connection',array('weight'=>$is_reverse[0]->weight -1));
		}
		
		$is_existed = $this->db->query("SELECT rs_connection.* FROM rs_connection
		 WHERE lower_content_id=$low AND upper_content_id=$high")->result();
		
		if(!empty($is_existed)){
			//check rs_post
			$r = $this->db->where(array('connection_id'=>$is_existed[0]->id, 'user_id'=>$user_id))->get('rs_post')->result();
			if(empty($r)){
				//insert into rs_post
				$this->db->insert('rs_post',array('connection_id'=>$is_existed[0]->id,'user_id'=>$user_id,'posted_time'=>time()));
				//increase 1 at rs_connection
				$this->db->where('id',$is_existed[0]->id)->update('rs_connection',array('weight'=>$is_existed[0]->weight +1,'last_posted_time'=>time(),'is_processed'=>0 ));
			}
		}else{
			//insert into rs_connection
			$this->db->insert('rs_connection',
			array('upper_content_id'=>$high,'lower_content_id'=>$low,'weight'=>1,'is_processed'=>0,'last_posted_time'=>time()));
			//insert into rs_post
			$connection_id= $this->db->insert_id();	
			$this->db->insert('rs_post',array('connection_id'=>$connection_id,'user_id'=>$user_id,'posted_time'=>time()));
		}
		*/
	}
	
	function connection_delete(){
		$id = intval($this->uri->segment(4));
		
		$this->db->where('id',$id)->delete('rs_connection');
		$this->db->where('connection_id',$id)->delete('rs_post');
		
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url('admin/dataman/connection/last_posted_time/desc/'));
	}
	
	/*///////////////////////////////////////USER AREA////////////////////////////////////////*/
	function user(){
		$config['base_url'] = site_url().'admin/dataman/user/';
		$config['total_rows'] = $this->dataman_m->get_total_user_records();
		$config['per_page'] = '25';
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = '&gt';
		$config['prev_link'] = '&lt';
		$config['cur_tag_open'] = '<div class="cur">';
		$config['cur_tag_close'] = '</div>';
		$config['uri_segment'] = '4';
		 
		$this->pagination->initialize($config);
	 	$contents = $this->dataman_m->get_user( $config['per_page'] , $this->uri->segment(4) );
		$this->data->contents = &$contents;
		$this->data->pagination = $this->pagination->create_links();
		
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.user'))
						->build('admin/user', $this->data);
	}
	
	function user_post(){
		$id = intval($this->uri->segment(4));
		
		$config['base_url'] = site_url()."admin/dataman/user_post/$id/";
		$config['total_rows'] = $this->dataman_m->get_total_user_post_records($id);
		$config['per_page'] = '25';
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = '&gt';
		$config['prev_link'] = '&lt';
		$config['cur_tag_open'] = '<div class="cur">';
		$config['cur_tag_close'] = '</div>';
		$config['uri_segment'] = '5';
		 
		$this->pagination->initialize($config);
	 	$contents = $this->dataman_m->get_user_post( $config['per_page'] , $this->uri->segment(5),$id ); 
		$this->data->contents = &$contents;
		$this->data->pagination = $this->pagination->create_links();
		$this->data->user_id = $id;
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.user'))
						->build('admin/user_post', $this->data);
	}
	
	function user_post_delete(){
		$connection_id = intval($this->uri->segment(4));
		$user_id = intval($_GET['user_id']);

		//decrease -1 at rs_connection
		$r = $this->db->where('id',$connection_id)->get('rs_connection')->result();
		$this->db->where('id',$connection_id)->update('rs_connection',array('weight'=>$r[0]->weight -1));
		
		//delete at rs_post
		$this->db->where(array('connection_id'=>$connection_id,'user_id'=>$user_id))->delete('rs_post');
		
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url("admin/dataman/user_post/$user_id"));
	}
	
	function aj_reject_user(){
		$id = $_POST['id'];
		$restrict_access = $_POST['reject'];
		
		$this->db->where('id',$id)->update('ff_users_fb',array('restrict_access'=>$restrict_access));
		echo lang('dataman.success');
		exit();
	}
	
	/*//////////////////////////////////////////////////VIOLATE CONTENT////////////////////////////////*/
	function violate(){
		$config['base_url'] = site_url()."admin/dataman/violate/";
		$config['total_rows'] = $this->dataman_m->get_total_violate_records();
		$config['per_page'] = '25';
		$config['full_tag_open'] = '<div id="pagination">';
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = '&gt';
		$config['prev_link'] = '&lt';
		$config['cur_tag_open'] = '<div class="cur">';
		$config['cur_tag_close'] = '</div>';
		$config['uri_segment'] = '4';
		 
		$this->pagination->initialize($config);
	 	$contents = $this->dataman_m->get_violate( $config['per_page'] , $this->uri->segment(4) ); 
		$this->data->contents = &$contents;
		$this->data->pagination = $this->pagination->create_links();
		 
		// Load the view
		$this->template->title($this->module_details['name'], lang('dataman.violate'))
						->build('admin/violate', $this->data);
	}
	
	function violate_delete(){
		$id = intval($this->uri->segment(4));
		
		$this->db->where('id',$id)->delete('ff_item_violate');
		$this->session->set_flashdata('success', lang('dataman.success'));
		
		redirect(site_url("admin/dataman/violate"));
	}
	
	
	
	
	
}
